# -*- coding: utf-8 -*-
# FileName:     zplayer.py
# time:         22/12/9 009 下午 2:26
# Author:       Zhou Hang
# Description:  I don't want to write
import os
import subprocess
import sys
from pathlib import Path

from PySide6.QtCore import Qt, QUrl
from PySide6.QtGui import QCloseEvent, QDesktopServices
from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog, QMenu

from src.gui.custom_module import RoundMainWindow
from src.gui.video_gui import ZVideoWidget
from src.ui.zplayer_ui import Ui_ZPlayer_mw
from qt_material import apply_stylesheet


class ZPlayerGui(RoundMainWindow, Ui_ZPlayer_mw):
    def __init__(self):
        super(ZPlayerGui, self).__init__()
        self.setupUi(self)
        self.video_wgt = ZVideoWidget()
        self.deal_with_project('../../video/example')

        self.start_btn.clicked.connect(self.video_start)
        self.selectdir_btn.clicked.connect(self.select_dir_btn)
        self.exit_btn.triggered.connect(self.exit_window)
        self.help_btn.triggered.connect(self.help_window)
        self.screenshot_list.itemClicked.connect(self.change_ppt)

    def exit_window(self):
        self.close()

    @staticmethod
    def help_window(self):
        """显示帮助文档，打开gitee网站README"""
        QDesktopServices.openUrl(QUrl("https://gitee.com/zhouzhoukang/raidsimulator"))

    def video_start(self):
        self.video_wgt.show()
        self.video_wgt.play()

    def deal_with_project(self, directory):
        ppts = self.video_wgt.set_ppt_dir(directory)
        # 这里得到所有视频的页码列表
        # 注意这里为了视频的顺序性做出的逻辑
        isExists = os.path.exists(f'{directory}/tmp')
        if not isExists:
            os.makedirs(f'{directory}/tmp')
        screen_shots = []
        for ppt in ppts:
            _input = f'{directory}/{ppt}.mp4'
            _output = f'{directory}/tmp/{ppt}.png'
            subprocess.Popen(f'ffmpeg -ss 00:02 -i {_input} {_output}')
            screen_shots.append(_output)
        self.screenshot_list.add_image_items(screen_shots)
        # 对获取到的所有mp4做截图操作，显示在list_widget中
        # ffmpeg -ss 00:02 -i .\Subset.mp4 -f image2 -r 1 -t 00:02 1.png
        # ffmpeg -ss 00:03 -i .\Subset.mp4 1.png
        # 这个命令可以实现截图，但是会报错，不明白原因，日后深入研究ffmpeg再说

    def select_dir_btn(self):
        """
        我的想法是将一系列ppt动画文件文件放在同一个文件夹下，用页码命名，使用快捷键来切换
        :return:
        """
        directory = QFileDialog.getExistingDirectory(self, "选择播放列表文件夹", "../../video")
        if directory != '':
            self.deal_with_project(directory)

    def change_ppt(self, item):
        self.video_wgt.set_cur_ppt(int(item.text()))

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            # self.close()
            pass
        # elif event.key() == Qt.Key_Return:

    def closeEvent(self, event: QCloseEvent) -> None:
        self.video_wgt.close()

    def contextMenuEvent(self, event):
        """右击触发菜单，有一个退出功能"""
        menu = QMenu(self)
        quitAction = menu.addAction("退出")
        action = menu.exec(self.mapToGlobal(event.pos()))
        if action == quitAction:
            self.close()


def main():
    app = QApplication(sys.argv)
    view = ZPlayerGui()
    extra = {'font_size': '15px',
             'font_family': '得意黑'}
    apply_stylesheet(app, theme='dark_amber.xml', extra=extra)

    view.show()
    sys.exit(app.exec())


if __name__ == "__main__":
    main()
